package org.springblade.modules.task;

import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import org.apache.commons.io.FileUtils;
import org.springblade.common.constant.LndxKTConstants;
import org.springblade.common.utils.LndxUtils;
import org.springblade.modules.app.entity.LndxCourse;
import org.springblade.modules.app.entity.LndxFile;
import org.springblade.modules.app.service.LndxFileService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.StringUtils;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;

@Configuration
@EnableScheduling
public class MkdirByTodayTask {


    @Autowired
    private LndxFileService lndxFileService;

    ///每天凌晨创建当日文件夹 格式如下 E:/20200919
    @Scheduled(cron = "0 0 1 * * ?")
    public void mkdirByToDay() {
        String todayPath = LndxUtils.getNowDateForyyyyMMdd();
        File filepath_rt = new File(LndxKTConstants.FILE_PATH_RT + todayPath);
        if (!filepath_rt.exists() && !filepath_rt.isDirectory()) {
            System.out.println("Init files directory");
            filepath_rt.mkdirs();
        } else {
            System.out.println("Already have this dictory");
        }
    }

    ///每天23点时 迁移 当日文件夹归档到 lndx文件夹下
    @Scheduled(cron = "0 0 23 * * ?")
    public void moveTodayDirectoryFile() {
        //原文件夹位置 E:/home/20200921
        String todayPath = LndxUtils.getNowDateForyyyyMMdd();
        File oldDirectory = new File(LndxKTConstants.FILE_PATH_RT + todayPath);
        //新文件件夹位置 E:/home/lndx
        File newDirectory = new File(LndxKTConstants.FILE_PATH_RT + LndxKTConstants.FILE_PATH_FILEDIC + "/");
        //文件迁移
        try {
            FileUtils.moveDirectoryToDirectory(oldDirectory,newDirectory,false);
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 批量更改 lndx_file表里的 filedic为lndx
        LambdaUpdateWrapper <LndxFile> lambdaUpdateWrapper = new LambdaUpdateWrapper();
        lambdaUpdateWrapper.and(wrapper -> wrapper.eq(LndxFile::getFilepath, todayPath));
        List<LndxFile> lndxFiles = lndxFileService.list(lambdaUpdateWrapper);
        for (LndxFile entity: lndxFiles) {
            entity.setFiledic(LndxKTConstants.FILE_PATH_FILEDIC);
            lndxFileService.updateById(entity);
        }

    }






}
